package com.cwj.we.module.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;

import com.cwj.we.R;
import com.cwj.we.base.BaseFragment;
import com.cwj.we.base.BasePresenter;
import com.cwj.we.bean.EventBG;
import com.cwj.we.common.GlobalConstant;
import com.cwj.we.http.API;
import com.cwj.we.module.about.AboutActivity;
import com.cwj.we.module.activity.ChuxidaojishiActivity;
import com.cwj.we.module.activity.SetTimeActivity;
import com.cwj.we.utils.LunarUtils;
import com.cwj.we.utils.NotificationUtils;
import com.cwj.we.utils.OneClickThree;
import com.cwj.we.utils.PictureSelectorUtils;
import com.cwj.we.utils.TimeUtils;
import com.cwj.we.utils.ToastUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.nlf.calendar.Lunar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我们
 */
public class UsFragment extends BaseFragment {

    @BindView(R.id.tv_together_time)
    TextView tv_together_time;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_time2)
    TextView tvTime2;
    @BindView(R.id.tv_in_harness_year)
    TextView tvInHarnessYear;
    @BindView(R.id.tv_get_married_year)
    TextView tvGetMarriedYear;
    @BindView(R.id.tv_change_date)
    TextView tvChangeDate;
    @BindView(R.id.tv_about)
    TextView tvAbout;
    @BindView(R.id.tv_set_backgground)
    TextView tvSetBackgground;
    @BindView(R.id.tv_reset)
    TextView tvReset;
    @BindView(R.id.tv_wedding_day)
    TextView tvWeddingDay;
    @BindView(R.id.tv_fall_in_love)
    TextView tvFallInLove;
    @BindView(R.id.hsv)
    HorizontalScrollView hsv;
    @BindView(R.id.tv_wedding_day_tip)
    TextView tvWeddingDayTip;
    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.ll_zaiyiqi_year)
    LinearLayout llZaiyiqiYear;
    @BindView(R.id.ll_jiehun_year)
    LinearLayout llJiehunYear;
    @BindView(R.id.ll_jiehunjinian)
    LinearLayout llJiehunjinian;
    @BindView(R.id.ll_zaiyiqijinian)
    LinearLayout llZaiyiqijinian;
    @BindView(R.id.ll_zaiyiqi)
    LinearLayout llZaiyiqi;
    @BindView(R.id.tv_yincang1)
    TextView tvYincang1;
    @BindView(R.id.tv_yincang2)
    TextView tvYincang2;
    @BindView(R.id.tv_yincang4)
    TextView tvYincang4;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.ic)
    View ic;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.tvChuxi)
    TextView tvChuxi;
    @BindView(R.id.tvChixiTip)
    TextView tvChixiTip;
    @BindView(R.id.cvChuxi)
    CardView cvChuxi;

    private String togetherTime;
    private String getMarriedTime;
    private String getMarriedTime2;
    private String getMarriedTime3;
    SharedPreferences sprfMain;
    private boolean isFrist = true;
    private boolean isFrist2 = true;
    private boolean isFrist3 = true;
    private BasePopupView popupView;
    private ActivityResultLauncher<Intent> launcherSearch;
    private ActivityResultLauncher<Intent> launcherChuxi;

    /**
     * 查询日期
     */
    @SuppressLint("SetTextI18n")
    private void queryPostAuthor() {
        tvYincang1.setVisibility(View.GONE);
        tvYincang2.setVisibility(View.GONE);
        tvYincang4.setVisibility(View.GONE);
        tvWeddingDayTip.setVisibility(View.GONE);

        togetherTime = API.kv.decodeString("togetherTime");
        getMarriedTime = API.kv.decodeString("getMarriedTime");
        getMarriedTime2 = API.kv.decodeString("getMarriedTime2");
        getMarriedTime3 = API.kv.decodeString("getMarriedTime3");
        if (popupView.isShow()) {
            popupView.smartDismiss();
        }
        if (togetherTime != null && getMarriedTime != null && getMarriedTime2 != null
                && getMarriedTime3 != null) {
            tvYincang1.setVisibility(View.VISIBLE);
            tvYincang2.setVisibility(View.VISIBLE);
            tvYincang4.setVisibility(View.VISIBLE);
            tvWeddingDayTip.setVisibility(View.VISIBLE);

            rl.setVisibility(View.VISIBLE);
            ic.setVisibility(View.GONE);
            tvTime.setText(togetherTime + " 我们在一起");
            tvTime2.setText(getMarriedTime + " 我们结婚");
            update();//显示数据
            //开始计时
            handler.postDelayed(runnable, 1000);
            //停止计时
            //handler.removeCallbacks(runnable);
            isFrist = true;
            isFrist2 = true;
            isFrist3 = true;
        } else {
            startActivity(new Intent(getActivity(), SetTimeActivity.class));
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_us;
    }

    protected void initView() {
        EventBus.getDefault().register(this);
        if (getActivity() != null) {
            sprfMain = getActivity().getSharedPreferences("counter", Context.MODE_PRIVATE);
        }
        popupView = new XPopup.Builder(getActivity())
                .dismissOnTouchOutside(false) // 点击外部是否关闭弹窗，默认为true
                .asLoading("")
                .show();
        queryPostAuthor();

        //日期修改回调
        launcherSearch = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {//判断是否返回成功
                        queryPostAuthor();//刷新数据
                    }
                });

        //除夕倒计时是否显示
        launcherChuxi = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {//判断是否返回成功
                        chuxiDaojisi();
                    }
                });

        chuxiDaojisi();
    }

    private void chuxiDaojisi() {
        //为false时显示除夕倒计时
        if (!API.kv.decodeBool(GlobalConstant.chuxi)) {
            cvChuxi.setVisibility(View.VISIBLE);
        } else {
            cvChuxi.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        ic.setOnClickListener(v -> {//刷新
            queryPostAuthor();
            popupView = new XPopup.Builder(getActivity())
                    .dismissOnTouchOutside(false) // 点击外部是否关闭弹窗，默认为true
                    .asLoading("")
                    .show();
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                if (popupView.isShow()) {
                    popupView.smartDismiss();
                }
            }, 1000 * 3);
        });

        //除夕倒计时详情查看
        cvChuxi.setOnClickListener(view -> startActivity(new Intent(getActivity(),
                ChuxidaojishiActivity.class)));
    }

    public static Handler handler = new Handler(Looper.getMainLooper());

    public Runnable runnable = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        public void run() {
            update();//获取新数据
            handler.postDelayed(this, 1000); //n秒刷新一次
        }
    };

    @SuppressLint("SetTextI18n")
    private void update() {
        long nowTime, startTime, apartTime, remainderHour, remainderMinute, remainderSecond,
                thisYearTogetherTimestamp, nextyearTogetherTimestamp, thisYearGetMarriedTimestamp,
                nextyearGetMarriedTimestamp, getLunarTimestamp = 0, thisYearTimestamp, chuxiDay,
                chuxiHoue, chuxiMinute, chuxiSecond;
        int inHarnessYear, getMarriedYear, setTogetherTime, setGetMarriedTime;
        String setTogetherDate, thisYearTogetherDate, nextyearTogetherDate, thisYearGetMarriedDate,
                nextyearGetMarriedDate, getLunarnowTime, thisYearDate;
        try {
            nowTime = TimeUtils.getTimeStame();//当前时间戳
            startTime = Long.parseLong(TimeUtils.dateToStamp2(togetherTime));//在一起的时间
            apartTime = (nowTime - startTime) / (1000 * 60 * 60 * 24);//天数
            remainderHour = ((nowTime - startTime) / (1000 * 60 * 60)) % 24;//小时
            remainderMinute = ((nowTime - startTime) / (1000 * 60)) % 60;//分钟
            remainderSecond = ((nowTime - startTime) / 1000) % 60;//秒
            tv_together_time.setText(apartTime + "天" + remainderHour + "小时" + remainderMinute
                    + "分" + remainderSecond + "秒");

            setTogetherTime = Integer.parseInt(togetherTime.substring(0, 4));//取出在一起年
            setGetMarriedTime = Integer.parseInt(getMarriedTime.substring(3, 7));//取出结婚年
            setTogetherDate = togetherTime.substring(4, 10);//取出在一起月日
            thisYearDate = TimeUtils.dateToString(nowTime, "yyyy-MM-dd");//当前年月日
            thisYearTogetherDate = TimeUtils.dateToString(nowTime, "yyyy") + setTogetherDate;//取出今年在一起的年月日
            nextyearTogetherDate = (Integer.parseInt(TimeUtils.dateToString(nowTime, "yyyy")) + 1)
                    + setTogetherDate;//取出下一年在一起的年月日
            thisYearTimestamp = Long.parseLong(TimeUtils.dateToStamp2(thisYearDate));//当前年月日的时间戳
            thisYearTogetherTimestamp = Long.parseLong(TimeUtils.dateToStamp2(thisYearTogetherDate));//今年在一起的年月日的时间戳
            nextyearTogetherTimestamp = Long.parseLong(TimeUtils.dateToStamp2(nextyearTogetherDate));//下一年在一起的年月日的时间戳

            //除夕倒计时
            Lunar d = Lunar.fromDate(new Date());
            Lunar lunar = Lunar.fromYmd(d.getYear() + 1, 1, 1);
            //获取春节为阳历几号
            String chunjieYL = lunar.getSolar() + " 00:00:00";
            //除夕时间戳
            long chuxiL = Long.parseLong(TimeUtils.dateToStamp(chunjieYL)) - 1000 * 60 * 60 * 24;
            //距离除夕还剩多少天
            chuxiDay = (chuxiL - nowTime) / (1000 * 60 * 60 * 24);//天数
            chuxiHoue = ((chuxiL - nowTime) / (1000 * 60 * 60)) % 24;//小时
            chuxiMinute = ((chuxiL - nowTime) / (1000 * 60)) % 60;//分钟
            chuxiSecond = ((chuxiL - nowTime) / 1000) % 60;//秒
            tvChixiTip.setText("距离除夕还有");
            if ((chuxiL - nowTime) > 0) {
                tvChuxi.setText(chuxiDay + "天" + chuxiHoue + "小时" + chuxiMinute + "分" + chuxiSecond
                        + "秒");
            } else {
                tvChuxi.setText("今天是除夕，新年快乐！");
                if (isFrist3) {
                    NotificationUtils.showNotification(getActivity(), "新年祝福通知",
                            "今天是除夕，新年快乐！", 3, "新年祝福通知",
                            100, 0);
                    isFrist3 = false;
                }
            }

            try {
                getLunarnowTime = TimeUtils.dateToString(nowTime, "yyyy-MM-dd");
                getLunarTimestamp = Long.parseLong(TimeUtils.dateToStamp2(getLunarnowTime));//得到当前的时间戳
            } catch (Exception e) {
                e.printStackTrace();
            }
            String thisyeargetMarriedTime;
            String nextyeargetMarriedTime;
            if ("闰".equals(getMarriedTime3.substring(5, 6))) {//2020-闰04-01
                thisYearGetMarriedDate = TimeUtils.dateToString(nowTime, "yyyy") + "-"
                        + getMarriedTime3.substring(6, 11);//取出今年结婚的年月日
                nextyearGetMarriedDate = (Integer.parseInt(TimeUtils.dateToString(nowTime,
                        "yyyy")) + 1) + "-" + getMarriedTime3.substring(6, 11);//取出下一年结婚的年月日

                int year = Integer.parseInt(thisYearGetMarriedDate.substring(0, 4));
                int month = Integer.parseInt(thisYearGetMarriedDate.substring(5, 7));
                int monthDay = Integer.parseInt(thisYearGetMarriedDate.substring(8, 10));
                thisyeargetMarriedTime = LunarUtils.getTranslateSolarString(year, month, monthDay);

                int nextyear = Integer.parseInt(nextyearGetMarriedDate.substring(0, 4));
                int nextmonth = Integer.parseInt(nextyearGetMarriedDate.substring(5, 7));
                int nextmonthDay = Integer.parseInt(nextyearGetMarriedDate.substring(8, 10));
                nextyeargetMarriedTime = LunarUtils.getTranslateSolarString(nextyear, nextmonth,
                        nextmonthDay);
            } else {//2020-04-01
                thisYearGetMarriedDate = TimeUtils.dateToString(nowTime, "yyyy")
                        + getMarriedTime3.substring(4, 10);//取出今年结婚的年月日
                nextyearGetMarriedDate = (Integer.parseInt(TimeUtils.dateToString(nowTime,
                        "yyyy")) + 1) + getMarriedTime3.substring(4, 10);//取出下一年结婚的年月日

                int year = Integer.parseInt(thisYearGetMarriedDate.substring(0, 4));
                int month = Integer.parseInt(thisYearGetMarriedDate.substring(5, 7));
                int monthDay = Integer.parseInt(thisYearGetMarriedDate.substring(8, 10));
                thisyeargetMarriedTime = LunarUtils.getTranslateSolarString(year, month, monthDay);

                int nextyear = Integer.parseInt(nextyearGetMarriedDate.substring(0, 4));
                int nextmonth = Integer.parseInt(nextyearGetMarriedDate.substring(5, 7));
                int nextmonthDay = Integer.parseInt(nextyearGetMarriedDate.substring(8, 10));
                nextyeargetMarriedTime = LunarUtils.getTranslateSolarString(nextyear, nextmonth,
                        nextmonthDay);
            }
            thisYearGetMarriedTimestamp = Long.parseLong(TimeUtils.dateToStamp2(thisyeargetMarriedTime));//今年结婚的年月日的时间戳
            nextyearGetMarriedTimestamp = Long.parseLong(TimeUtils.dateToStamp2(nextyeargetMarriedTime));//下一年结婚的年月日的时间戳

            inHarnessYear = Integer.parseInt(TimeUtils.dateToString(nowTime, "yyyy"))
                    - setTogetherTime;//在一起年数
            getMarriedYear = Integer.parseInt(TimeUtils.dateToString(nowTime, "yyyy"))
                    - setGetMarriedTime;//结婚年数
            tvInHarnessYear.setText(inHarnessYear + "年");

            //相恋日提醒
            if ((thisYearTogetherTimestamp - thisYearTimestamp) > 0) {
                tvFallInLove.setText((thisYearTogetherTimestamp - thisYearTimestamp) / 1000 / 60 / 60 / 24
                        + "天");//相恋纪念日
            } else if ((thisYearTogetherTimestamp - thisYearTimestamp) == 0) {
                tvFallInLove.setText(0 + "天");
                if (inHarnessYear > 0) {
                    if (isFrist) {
                        NotificationUtils.showNotification(getActivity(), "相恋日通知",
                                "今天是你们相恋的" + inHarnessYear + "周年，问候ta一下吧!",
                                1, "相恋日通知", 100, 0);
                        isFrist = false;
                    }
                }
            } else {
                tvFallInLove.setText((nextyearTogetherTimestamp - thisYearTimestamp)
                        / 1000 / 60 / 60 / 24 + "天");
            }

            long getMarriedTimestamp = Long.parseLong(TimeUtils.dateToStamp2(getMarriedTime2));//阳历结婚时间毫秒数
            if ((thisYearTimestamp - getMarriedTimestamp) >= 0) {
                tvGetMarriedYear.setText(getMarriedYear + "年");
            } else {
                tvGetMarriedYear.setText(0 + "年");
            }

            //结婚纪念日提醒
            if ((thisYearGetMarriedTimestamp - getLunarTimestamp) > 0 && ((getMarriedTimestamp
                    - thisYearTimestamp) / 1000 / 60 / 60 / 24) < 0) {
                tvWeddingDayTip.setText("距结婚纪念日还有");
                tvWeddingDay.setText((thisYearGetMarriedTimestamp - getLunarTimestamp)
                        / 1000 / 60 / 60 / 24 + "天");//结婚纪念日
            } else if ((thisYearGetMarriedTimestamp - getLunarTimestamp) == 0) {
                tvWeddingDayTip.setText("距结婚纪念日还有");
                tvWeddingDay.setText(0 + "天");
                if (getMarriedYear > 0) {
                    if (isFrist2) {
                        NotificationUtils.showNotification(getActivity(), "结婚纪念日通知",
                                "今天是你们的" + getMarriedYear + "周年结婚纪念日，记得给ta一个惊喜哦!",
                                2, "结婚纪念日通知", 100, 0);
                        isFrist2 = false;
                    }
                }
            } else if (((getMarriedTimestamp - thisYearTimestamp) / 1000 / 60 / 60 / 24) > 0) {
                tvWeddingDayTip.setText("距结婚还有");
                tvWeddingDay.setText((getMarriedTimestamp - thisYearTimestamp) / 1000 / 60 / 60 / 24
                        + "天");//结婚纪念日
            } else {
                tvWeddingDayTip.setText("距结婚纪念日还有");
                tvWeddingDay.setText((nextyearGetMarriedTimestamp - getLunarTimestamp) / 1000 / 60 / 60 / 24
                        + "天");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void doCode() {
        PictureSelectorUtils.ofImage(this, REQUEST_CODE_SELECT_USER_ICON);
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //执行代码,这里是已经申请权限成功了,可以不用做处理
                doCode();
            } else {
                Toast.makeText(getActivity(), "权限申请失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    SharedPreferences.Editor editorMain;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_SELECT_USER_ICON) {
                String userIconPath = PictureSelectorUtils.forResult(resultCode, data);
                if (userIconPath == null) {
                } else {
                    EventBG eventBG = new EventBG("EVENT_SZ_BG", userIconPath);
                    EventBus.getDefault().post(eventBG);

                    sprfMain = getActivity().getSharedPreferences("counter", Context.MODE_PRIVATE);
                    editorMain = sprfMain.edit();
                    editorMain.putString("path", userIconPath);
                    editorMain.apply();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBG eventBG) {
        if (GlobalConstant.ChangePassword_SUCCESS.equals(eventBG.getType())) {//修改密码成功
            //停止计时
            handler.removeCallbacks(runnable);
        }
    }

    private static final int REQUEST_CODE_SELECT_USER_ICON = 100;

    @OnClick({R.id.tv_change_date, R.id.tv_about, R.id.tv_set_backgground, R.id.tv_reset})
    public void onViewClicked(View view) {
        Intent intent;
        int id = view.getId();
        if (id == R.id.tv_change_date) {//日期修改
            if (!OneClickThree.isFastClick()) {
                intent = new Intent(getActivity(), SetTimeActivity.class);
                intent.putExtra("setTime", 2);
                launcherSearch.launch(intent);
            }
        } else if (id == R.id.tv_about) {//关于
            if (!OneClickThree.isFastClick()) {
                intent = new Intent(getActivity(), AboutActivity.class);
                launcherChuxi.launch(intent);
            }
        } else if (id == R.id.tv_set_backgground) {//设置背景
            if (!OneClickThree.isFastClick()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        //没有权限则申请权限
                        this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                1);
                    } else {
                        //有权限直接执行,docode()不用做处理
                        doCode();
                    }
                } else {
                    //小于6.0，不用申请权限，直接执行
                    doCode();
                }
            }
        } else if (id == R.id.tv_reset) {//重置背景
            if (TextUtils.isEmpty(sprfMain.getString("path", ""))) {
                ToastUtil.showTextToast(getActivity(), "已经是原始背景,请勿重试！");
            } else {
                if (!OneClickThree.isFastClick()) {
                    new XPopup.Builder(getActivity()).asConfirm("提示", "确定重置当前背景吗？",
                                    () -> {
                                        editorMain = sprfMain.edit();
                                        editorMain.putString("path", "");
                                        editorMain.apply();

                                        EventBG eventBG = new EventBG("EVENT_CZ_BG", "");
                                        EventBus.getDefault().post(eventBG);
                                    })
                            .show();
                }
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
